import {
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import { Observable } from 'rxjs';
import { JwtService } from '@nestjs/jwt';
import { IS_PUBLIC_KEY } from '../utils/skip.jwt';
// import { Role } from 'src/roles/role.enum';
import { ROLES_KEY } from 'src/roles/roles.decorator';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwtStrategy') {
  constructor(
    private reflector: Reflector,
    private readonly jwtService: JwtService,
  ) {
    super();
  }

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (isPublic) {
      return true;
    }

    const roles = this.reflector.get<string[]>(ROLES_KEY, context.getHandler());
    if (!roles) {
      return super.canActivate(context);
    }

    const request = context.switchToHttp().getRequest();
    const authorization = request['headers'].authorization || 0;

    if (authorization) {
      const token = authorization.split(' ')[1];
      try {
        const payload = this.jwtService.decode(token);

        if (roles.includes(payload.role)) {
          return super.canActivate(context);
        } else {
          throw new UnauthorizedException('当前用户暂无访问权限');
        }
      } catch (e) {
        // 执行
        throw new UnauthorizedException('暂无访问权限');
      }
    }

    return super.canActivate(context);
  }

  handleRequest(err, user, info) {
    // 您可以基于 "info" 或 "err" 参数抛一个错误
    if (err || !user) {
      throw err || new UnauthorizedException('登录超时');
    }
    return user;
  }
}
